import { defineComponent, onMounted, type PropType, ref, toRefs, unref } from 'vue'
import { Button, Card, Form, FormItem, Input, Select, Table, Textarea } from 'ant-design-vue'
import { useDetail } from './use-detail'
import { useForm } from './use-form'
import { BusinessPageTypeEnum } from '@/enums/pageTypeEnum'
import { useColumns } from '@/views/warehouse/purchase-order/detail/use-detail-columns'
import { arrivalStatusObj } from '@/views/warehouse/purchase-order/data'
import { sheLfEnum } from '@/views/base/product/data'

const props = {
  code: {
    type: [String, Number],
    required: false
  },
  businessType: {
    type: String as PropType<BusinessPageTypeEnum>,
    required: true,
    validator: (value: string) => {
      // 检查传入的值是否在枚举的有效值中
      return Object.values(BusinessPageTypeEnum).includes(value as BusinessPageTypeEnum)
    }
  }
}

const DataDetail = defineComponent({
  emits: ['cancelModal', 'confirmModal'],
  props,
  name: 'DataDetail',
  setup(props, ctx) {
    const { meta, state, initForm, getFormValues } = useForm()
    const {
      status,
      createOrUpdate,
      getDataById,
      getBrandOptions,
      getWarehouseList,
      getProductOptions,
      getProductByCode,
      updatePurchaseOrderDetailProductStatus
    } = useDetail(getFormValues)
    const brandOptionData = ref<any[]>([])
    const warehouseOptionData = ref<any[]>([])
    const productOptionData = ref<any[]>([])
    const tableData = ref<any[]>([])
    const totalAmount = ref(0)

    const deleteRow = (key: any) => {
      tableData.value?.splice(key, 1)
    }
    const addRow = () => {
      tableData.value?.push({})
    }

    const setProductToTableData = async (code: string, index: number) => {
      const selectProduct = await getProductByCode(code)
      tableData.value[index].productCode = selectProduct.code
      tableData.value[index].productName = selectProduct.name
      tableData.value[index].productUniqueCode = selectProduct.productUniqueCode
      tableData.value[index].productSpecification = selectProduct.specificationNumber + selectProduct.specificationName
      tableData.value[index].productPacking = selectProduct.packingNumber + selectProduct.packingName
      let shelfLifeUnitStr = ''
      sheLfEnum.forEach(model => {
        if (model.value == selectProduct.shelfLifeUnit) {
          shelfLifeUnitStr = model.label
        }
      })
      tableData.value[index].productShelfLife = selectProduct.shelfLife + shelfLifeUnitStr
      tableData.value[index].purchasingPrice = selectProduct.actualPrice
    }

    // 更新总金额
    const resetTotalAmount = () => {
      totalAmount.value = 0
      for (let i = 0; i < tableData.value.length; i++) {
        totalAmount.value += tableData.value[i].purchasingPrice * tableData.value[i].purchaseNumber
      }
    }

    // 更改付款状态
    const payment = async (index: any) => {
      const paymentStatusResult = await updatePurchaseOrderDetailProductStatus(tableData.value[index].code)
      if (paymentStatusResult == true) {
        tableData.value[index].paymentStatus = 1
      }
    }

    const { getColumns, tableColumns } = useColumns(
      deleteRow,
      setProductToTableData,
      resetTotalAmount,
      payment,
      productOptionData,
      props.businessType
    )

    const checkSimple = (index: any) => {
      if (!tableData.value[index].productCode) {
        window.alert('请选择产品')
        return false
      }
      if (!tableData.value[index].purchaseNumber) {
        window.alert('请输入采购数量')
        return false
      }
      return true
    }

    const checkFormData = () => {
      if (!state.detailForm.brandProviderCode) {
        window.alert('请选择品牌方')
        return false
      }
      if (!state.detailForm.warehouseCode) {
        window.alert('请选择仓库')
        return false
      }
      if (tableData.value?.length < 0) {
        window.alert('采购单采购列表至少有一条数据')
        return false
      }
      for (let i = 0; i < tableData.value.length; i++) {
        if (!checkSimple(i)) {
          return false
        }
      }
      return true
    }

    const handleCommit = async () => {
      if (checkFormData()) {
        state.detailForm.purchaseOrderDetailFormList = tableData.value
        for (let i = 0; i < brandOptionData.value.length; i++) {
          if (state.detailForm.brandProviderCode === brandOptionData.value[i].value) {
            state.detailForm.brandProviderName = brandOptionData.value[i].label
          }
        }
        for (let i = 0; i < warehouseOptionData.value.length; i++) {
          if (state.detailForm.warehouseCode === warehouseOptionData.value[i].value) {
            state.detailForm.warehouseName = warehouseOptionData.value[i].label
          }
        }
        await createOrUpdate()
        initForm()
        ctx.emit('confirmModal')
      }
    }

    const resetForm = () => {
      initForm()
      ctx.emit('cancelModal')
    }

    onMounted(async () => {
      await fetchData()
      brandOptionData.value = await getBrandOptions()
      warehouseOptionData.value = await getWarehouseList()
      productOptionData.value = await getProductOptions()
      resetTotalAmount()
    })

    const fetchData = async () => {
      if (props.businessType === BusinessPageTypeEnum.UPDATE || props.businessType === BusinessPageTypeEnum.DETAIL) {
        // 查询值
        state.detailForm = await getDataById(props.code)
        tableData.value = state.detailForm.purchaseOrderDetailFormList
      }
    }

    return {
      ...toRefs(props),
      ...toRefs(state),
      ...toRefs(status),
      ...toRefs(meta),
      brandOptionData,
      warehouseOptionData,
      getColumns,
      tableColumns,
      tableData,
      totalAmount,
      addRow,
      deleteRow,
      handleCommit,
      resetForm
    }
  },
  render() {
    const {
      businessType,
      detailForm,
      rules,
      brandOptionData,
      warehouseOptionData,
      getColumns,
      tableColumns,
      tableData,
      totalAmount,
      addRow,
      handleCommit,
      resetForm
    } = this
    // @ts-ignore
    return (
      <>
        <Card>
          <Form
            ref='detailFormRef'
            model={detailForm}
            rules={rules}
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 17 }}
            style={{ width: '80%' }}
            onFinish={handleCommit}
          >
            <FormItem label='发货品牌方' name='brandProviderCode'>
              <Select
                disabled={businessType !== BusinessPageTypeEnum.ADD}
                mode='single'
                v-model={[detailForm.brandProviderCode, 'value']}
                options={brandOptionData}
              />
            </FormItem>
            <FormItem label='收货仓库' name='warehouseCode'>
              <Select
                disabled={businessType !== BusinessPageTypeEnum.ADD}
                mode='single'
                v-model={[detailForm.warehouseCode, 'value']}
                options={warehouseOptionData}
              />
            </FormItem>
            <FormItem label='到货状态' name='arrivalStatus'>
              <Select
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                mode='single'
                v-model={[detailForm.arrivalStatus, 'value']}
                options={arrivalStatusObj}
              />
            </FormItem>
            <FormItem label='订单总金额' name='totalAmount'>
              <Input disabled mode='single' v-model={[totalAmount, 'value']} />
            </FormItem>
            <FormItem label='备注' name='description'>
              <Textarea
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                v-model={[detailForm.remark, 'value']}
                maxlength={200}
                rows={3}
              />
            </FormItem>
            <Card>
              {businessType != BusinessPageTypeEnum.DETAIL && (
                <Button type='primary' onClick={addRow}>
                  新增一行
                </Button>
              )}
              <br />
              <Table
                rowKey='id'
                columns={
                  businessType != BusinessPageTypeEnum.DETAIL
                    ? tableColumns
                    : tableColumns.slice(0, tableColumns.length - 1)
                }
                style={{ width: '1000px' }}
                dataSource={unref(tableData)}
                pagination={false}
                bordered
              >
                {{
                  bodyCell: ({ column, record, index }) => getColumns(column, record, index)
                }}
              </Table>
            </Card>
            <FormItem wrapperCol={{ span: 12, offset: 12 }}>
              {businessType === BusinessPageTypeEnum.DETAIL && <Button onClick={resetForm}>返回</Button>}
              {businessType !== BusinessPageTypeEnum.DETAIL && (
                <>
                  <Button type='primary' htmlType='submit'>
                    提交
                  </Button>
                  <Button style={{ marginLeft: '12px' }} onClick={resetForm}>
                    取消
                  </Button>
                </>
              )}
            </FormItem>
          </Form>
        </Card>
      </>
    )
  }
})
export default DataDetail
